package com.muc.plugin.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import com.muc.plugin.dao.hander.BindSQLProperty;
import org.jivesoftware.database.DbConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.muc.plugin.vo.PubEntity;

/**
 * @author lyusantu@gmail.com
 */
public class CommonDAO {

    private static final Logger log = LoggerFactory.getLogger(CommonDAO.class);

    public static PubEntity get(String sql, Object[] param) {
        List<PubEntity> list = query(sql, param);
        return (list != null && list.size() > 0) ? list.get(0) : null;
    }

    public static List<PubEntity> query(String sql, Object[] param) {
        ResultSet rs = null;
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(sql);
            int index = 1;
            for (Object o : param) {
                if (o instanceof String) {
                    pstmt.setString(index, String.valueOf(o));
                } else if (o instanceof Integer) {
                    pstmt.setInt(index, Integer.valueOf(o + ""));
                } else {
                    pstmt.setString(index, String.valueOf(o));
                }
                index++;
            }
            rs = pstmt.executeQuery();
            List<PubEntity> list = BindSQLProperty.findBySQL(rs);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("query common fail：" + e.getMessage());
        } finally {
            DbConnectionManager.closeConnection(rs, pstmt, con);
        }
        return null;
    }

}
